package cn.zhejianglao.oss.controller;


import cn.zhejianglao.oss.common.Response;
import cn.zhejianglao.oss.config.HostProperties;
import cn.zhejianglao.oss.service.IFileStorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private IFileStorageService fileStorageService;

    @Autowired
    private HostProperties hostProperties;

    @PostMapping("/upload")
    public Response upload(@RequestParam("file") MultipartFile file) {
        String fileName = fileStorageService.storeFile(file);

//        String servingUrl = hostProperties + fileName;

        return Response.ok(fileName);
    }

    @GetMapping("/download/{fileName}")
    public ResponseEntity<Resource> download(
            @PathVariable("fileName") String fileName,
            HttpServletRequest request) {

        Resource resource = fileStorageService.loadFileAsResource(fileName);
        String contentType = null;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException ex) {
            log.info("Could not determine file type.");
        }

        // Fallback to the default content type if type could not be determined
        if(contentType == null) {
            contentType = "application/octet-stream";
        }

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(resource);
    }

    @DeleteMapping("/delete/{fileName}")
    public Response deleteFile(@PathVariable("fileName") String fileName) {
        fileStorageService.delete(fileName);
        return Response.ok();
    }

    @PostMapping("/replace")
    public Response replace(@RequestParam("file") MultipartFile file, @RequestParam("oldFileName") String oldFilename) {
        String fileName = fileStorageService.replace(file, oldFilename);
        String servingUrl = hostProperties + fileName;

        return Response.ok(servingUrl);
    }
}

